<template>
  <div class="header">
    <!-- 折叠按钮、logo、用户下拉等保持不变 -->
    <div class="collapse-btn" @click="collapseChage">
      <i v-if="!collapse" class="el-icon-s-fold"></i>
      <i v-else class="el-icon-s-unfold"></i>
    </div>
    <div class="logo">后台管理系统</div>
    <div class="header-right">
      <div class="header-user-con">
        <!-- 全屏 -->
        <div class="btn-fullscreen" @click="handleFullScreen">
          <el-tooltip effect="dark" :content="fullscreen ? `取消全屏` : `全屏`" placement="bottom">
            <i class="el-icon-rank"></i>
          </el-tooltip>
        </div>
        <!-- 用户头像 -->
        <div class="user-avator">
          <img src="../../assets/img/img.jpg" />
        </div>
        <!-- 用户名下拉 -->
        <el-dropdown class="user-name" trigger="click" @command="handleCommand">
          <span class="el-dropdown-link">
            管理员
            <i class="el-icon-caret-bottom"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
            <el-dropdown-item divided command="loginout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>

    <!-- 修改密码弹窗：两步式，第一步展示掩码手机号+验证码 -->
    <el-dialog
      title="修改密码"
      :visible.sync="changePasswordDialogVisible"
      width="400px"
      @close="resetChangeForm"
    >
      <template v-if="loadingUser">
        <div style="text-align: center; padding: 20px 0;">加载中...</div>
      </template>
      <template v-else>
        <el-form
          ref="changeFormRef"
          :model="changeForm"
          :rules="currentRules"
          label-width="100px"
          status-icon
        >
          <!-- 步骤1：展示掩码手机号 + 验证码输入 -->
          <template v-if="smsStep === 1">
            <el-form-item label="手机号">
              <!-- 只读展示掩码后的手机号 -->
              <el-input
                :value="maskedPhone"
                disabled
              />
            </el-form-item>
            <el-form-item label="验证码" prop="smsCode">
              <el-input
                v-model="changeForm.smsCode"
                placeholder="请输入短信验证码"
                maxlength="6"
              >
                <template slot="append">
                  <el-button
                    size="small"
                    :disabled="sendSmsLoading || !hasValidPhone"
                    @click="sendSms"
                  >
                    <span v-if="countdown > 0">{{ countdown }}s后重发</span>
                    <span v-else>发送验证码</span>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </template>

          <!-- 步骤2：输入新密码 -->
          <template v-else-if="smsStep === 2">
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="changeForm.newPassword"
                type="password"
                autocomplete="new-password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="changeForm.confirmPassword"
                type="password"
                autocomplete="new-password"
                placeholder="请再次输入新密码"
                show-password
              />
            </el-form-item>
          </template>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button
            v-if="smsStep === 1"
            type="primary"
            :loading="verifyLoading"
            @click="verifySmsCode"
          >下一步</el-button>
          <el-button
            v-else-if="smsStep === 2"
            type="primary"
            :loading="changeLoading"
            @click="submitChangePassword"
          >提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import bus from '../common/bus';
import requests from '../../utils/request';

export default {
  name: 'HeaderBar',
  data() {
    return {
      collapse: false,
      fullscreen: false,
      name: 'linxin',

      // 修改密码流程相关
      changePasswordDialogVisible: false,
      smsStep: 1, // 当前步骤：1=手机号+验证码, 2=新密码
      loadingUser: false, // 正在加载当前用户信息
      realPhoneNumber: '', // 完整手机号，从后端拿到
      sendSmsLoading: false,
      verifyLoading: false,
      smsCode:'',
      changeLoading: false,
      countdown: 0,
      countdownTimer: null,
      form:{
        phone:null,
        newPassword:'',
        code:''
      },
      changeForm: {
        smsCode: '',
        newPassword: '',
        confirmPassword: '',
      },
      changeRules: {
        smsCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码为6位数字', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '新密码至少6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              if (!value) {
                callback(new Error('请再次输入新密码'));
              } else if (value !== this.changeForm.newPassword) {
                callback(new Error('两次输入密码不一致'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
      },
    };
  },
  computed: {
    username() {
      let username = this.$store.state.user.username;
      return username ? username : this.name;
    },
    // 掩码手机号展示，如 138****1234
    maskedPhone() {
      const p = this.realPhoneNumber;
      if (!p || p.length < 7) return '';
      // 常见中国手机号掩码: 前3后4
      return p.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
    },
    // 如果拿到合法手机号，才允许发送验证码
    hasValidPhone() {
      // 简单判：11位数字
      return /^1[3-9]\d{9}$/.test(this.realPhoneNumber);
    },
    // 返回当前表单校验规则
    currentRules() {
      if (this.smsStep === 1) {
        return {
          smsCode: this.changeRules.smsCode
        };
      } else if (this.smsStep === 2) {
        return {
          newPassword: this.changeRules.newPassword,
          confirmPassword: this.changeRules.confirmPassword
        };
      }
      return {};
    }
  },
  methods: {
    handleCommand(command) {
      if (command === 'loginout') {
        this.$router.push('/login');
        requests.post('/adminAccounts/logout');
      } else if (command === 'changePassword') {
        this.openChangeDialog();
      }
    },
    openChangeDialog() {
      // 每次打开都重置状态并加载用户信息
      this.resetChangeForm();
      this.smsStep = 1;
      this.changePasswordDialogVisible = true;
      this.fetchCurrentUserPhone();
    },
    collapseChage() {
      this.collapse = !this.collapse;
      bus.$emit('collapse', this.collapse);
    },
    handleFullScreen() {
      let element = document.documentElement;
      if (this.fullscreen) {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      } else {
        if (element.requestFullscreen) {
          element.requestFullscreen();
        } else if (element.webkitRequestFullScreen) {
          element.webkitRequestFullScreen();
        } else if (element.mozRequestFullScreen) {
          element.mozRequestFullScreen();
        } else if (element.msRequestFullscreen) {
          element.msRequestFullscreen();
        }
      }
      this.fullscreen = !this.fullscreen;
    },
    // 调用后端 /currentUser 拿手机号
    fetchCurrentUserPhone() {
      this.loadingUser = true;
      requests.get('/adminAccounts/currentUser')
        .then(response => {
          // 假设 response.data.username 就是手机号
          const phone = response  && response.username;
          if (phone && /^1[3-9]\d{9}$/.test(phone)) {
            this.realPhoneNumber = phone;
          } else {
            this.realPhoneNumber = '';
            this.$message.warning('未获取到有效手机号，请先绑定手机号');
            // 视业务决定：可以直接关闭弹窗或引导绑定
            // this.changePasswordDialogVisible = false;
          }
        })
        .catch(err => {
          console.error(err);
          this.realPhoneNumber = '';
          this.$message.error('获取当前用户信息失败');
          // 可视情况关闭弹窗或保持弹窗不可操作
        })
        .finally(() => {
          this.loadingUser = false;
        });
    },
    // 发送短信验证码到 realPhoneNumber
    sendSms() {
      if (!this.hasValidPhone) {
        this.$message.error('当前手机号不可用');
        return;
      }
      this.sendSmsLoading = true;
      this.form.phone = this.realPhoneNumber
      requests.post('/sms/sendCode',this.form)
        .then(response => {
          this.$message.success(response)
        })
        .catch(err => {
          console.error(err);
          this.$message.error('发送验证码出错');
        })
        .finally(() => {
          this.sendSmsLoading = false;
        });
    },
    startCountdown() {
      this.countdown = 60;
      if (this.countdownTimer) clearInterval(this.countdownTimer);
      this.countdownTimer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(this.countdownTimer);
          this.countdownTimer = null;
        }
      }, 1000);
    },
    // 验证短信验证码，进入第二步
verifySmsCode() {
  this.$refs.changeFormRef.validate(valid => {
    if (!valid) return;
    this.verifyLoading = true;
    this.form.phone = this.realPhoneNumber;
    requests.post('/sms/check-sms-code', this.form)
      .then(response => {
        if (response == 0) {
          this.smsStep = 2;
          this.$nextTick(() => {
            if (this.$refs.changeFormRef) {
              this.$refs.changeFormRef.resetFields();
            }
          });

        } else {
          this.$message.error(response.message || '验证码验证失败');
        }
      })
      .catch(err => {
        console.error(err);
        this.$message.error('验证码验证出错');
      })
      .finally(() => {
        this.verifyLoading = false;
      });
  });
},


    // 提交新密码
    submitChangePassword() {
      this.$refs.changeFormRef.validate(valid => {
        if (!valid) return;
        this.changeLoading = true;
        requests.post('/api/user/change-password-via-sms', {
          phone: this.realPhoneNumber,
          newPassword: this.changeForm.newPassword
        })
          .then(response => {
            if (response.success) {
              this.$message.success(response.message || '修改成功，请重新登录');
              this.changePasswordDialogVisible = false;
              this.resetChangeForm();
              // 可选：登出跳转
              this.$router.push('/login');
            } else {
              this.$message.error(response.message || '修改失败');
            }
          })
          .catch(err => {
            console.error(err);
            this.$message.error('修改出错');
          })
          .finally(() => {
            this.changeLoading = false;
          });
      });
    },
    handleCancel() {
      this.changePasswordDialogVisible = false;
      this.resetChangeForm();
    },
    resetChangeForm() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
        this.countdownTimer = null;
      }
      this.countdown = 0;
      this.smsStep = 1;
      this.realPhoneNumber = '';
      this.loadingUser = false;
      // 重置表单字段和校验
      if (this.$refs.changeFormRef) {
        this.$refs.changeFormRef.resetFields();
      }
      this.changeForm.smsCode = '';
      this.changeForm.newPassword = '';
      this.changeForm.confirmPassword = '';
      this.sendSmsLoading = false;
      this.verifyLoading = false;
      this.changeLoading = false;
    }
  },
  mounted() {
    if (document.body.clientWidth < 1500) {
      this.collapseChage();
    }
  },
  beforeDestroy() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
  }
};
</script>
<style scoped>
.header {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: 70px;
  font-size: 22px;
  color: #fff;
}
.collapse-btn {
  float: left;
  padding: 0 21px;
  cursor: pointer;
  line-height: 70px;
}
.header .logo {
  float: left;
  width: 250px;
  line-height: 70px;
}
.header-right {
  float: right;
  padding-right: 50px;
}
.header-user-con {
  display: flex;
  height: 70px;
  align-items: center;
}
.btn-fullscreen {
  transform: rotate(45deg);
  margin-right: 5px;
  font-size: 24px;
}
.btn-bell,
.btn-fullscreen {
  position: relative;
  width: 30px;
  height: 30px;
  text-align: center;
  border-radius: 15px;
  cursor: pointer;
}
.btn-bell-badge {
  position: absolute;
  right: 0;
  top: -2px;
  width: 8px;
  height: 8px;
  border-radius: 4px;
  background: #f56c6c;
  color: #fff;
}
.btn-bell .el-icon-bell {
  color: #fff;
}
.user-name {
  margin-left: 10px;
}
.user-avator {
  margin-left: 20px;
}
.user-avator img {
  display: block;
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.el-dropdown-link {
  color: #fff;
  cursor: pointer;
}
.el-dropdown-menu__item {
  text-align: center;
}
/* 可根据需要对弹窗内表单做微调 */
</style>
